package com.burgeon.backend.SHOPBACKEND.service.Impl;

import com.burgeon.backend.SHOP.mappers.GoodsMapper;

import com.burgeon.backend.SHOPBACKEND.entity.*;
import com.burgeon.backend.SHOPBACKEND.mappers.MaterialMapper;
import com.burgeon.backend.SHOPBACKEND.service.MaterialService;
import com.burgeon.backend.SHOPBACKEND.service.ex.DeleteException;
import com.burgeon.backend.SHOPBACKEND.service.ex.InsertException;
import com.burgeon.backend.SHOPBACKEND.service.ex.UploadException;
import com.burgeon.backend.mappers.AccountMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class MaterialServiceImpl implements MaterialService {
    private final static Log logger = LogFactory.getLog(MaterialService.class);

    @Autowired
    private MaterialMapper materialMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 新增素材分组
     * @param file
     * @param groupName
     * @param account
     * @return
     */
    @Override
    public Integer insertMaterialGroup(MultipartFile file, String groupName, String account) {
        String types = "group";
        if (null == file || file.isEmpty()) {
            System.err.println("文件为空");
            throw new UploadException("文件为空");
        }
        //文件名
        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //http://lfwdcdn.cloudsmicro.com/img/mgg-shop/2.png
        // 上传后的路径

        //获取token
        //String token = accountMapper.GetTokenForAccount(account);
        try {
            MaterialGroup materialGroup = new MaterialGroup();
            materialGroup.setGroupName(groupName);

            materialGroup.setAccount(account);
            //新增
            Integer row = materialMapper.insertMaterialGroup(materialGroup);

            materialGroup.setGroupImg("http://lfwd.cloudsmicro.com/img/" + account + "-material/" + materialGroup.getId() + "/" + materialGroup.getId() + suffixName);
            //将图片修改
            materialMapper.upGroup(materialGroup.getId(),materialGroup.getGroupImg());

            String filePath = "//root//code//img//" + account + "-material//" + materialGroup.getId() + "//";
            // 新文件名
            fileName = materialGroup.getId() + suffixName;
            saveFile(file, fileName, filePath);
            return row;
        }catch (Exception e){
            e.printStackTrace();
            throw new InsertException("新增错误");
        }

    }

    /**
     * 查询所有分组
     * @param account
     * @return
     */
    @Override
    public MaterialGroupVo findGroupByAccount(String account) {
        if (null == account || account.isEmpty()) {
            System.err.println("没有account");
            throw new UploadException("没有account");
        }
      //  int start = (page-1)*20;

        MaterialGroupVo materialGroupVo = new MaterialGroupVo();

        ArrayList<MaterialGroup> materialGroups = materialMapper.findGroupByAccount(account);
        materialGroupVo.setMaterialGroup(materialGroups);
        materialGroupVo.setCount(materialMapper.findGroupCount(account));

        return materialGroupVo;
    }

    private String toString(String[] data){

        return Arrays.toString(data).replace("\"","'")
                .replace("[","")
                .replace("]","")
                .replace(" ", "");

    }

    /**
     * 删除分组
     * @param ids
     * @param account
     * @return
     */
    @Override
    public void deGroupById(String ids, String account) throws JSONException {
       // String ids = "111,222,333,444";
        List<String> list = new ArrayList<>();
        String str[] = ids.split(",");
        list = Arrays.asList(str);
        //JSONArray jsonArray = new JSONArray(ids);
        // List<String> s  = JSONObject.parseArray(ids,String.class);

       for(String id : list) {


            //根据id和account删除素材分组
            Integer group = materialMapper.deGroupById(id,account);
            if(group == 1){
                //根据分组id删除素材
                Integer rma = materialMapper.deMaterialByGroupId(id);
                if(rma != 0) {
                    //根据分组id查看素材
                    ArrayList<Material> materials = materialMapper.findMaByGpId(id);
                    for (Material material : materials) {
                        //根据素材id删除图片
                        Integer rImgs = materialMapper.deMaterialImgs(material.getId());
                        if (rImgs != 0) {
                            //根据素材id查询图片
                            ArrayList<MaterialImgs> materialImgs = materialMapper.findMaImgsByGpId(material.getId());
                            for (MaterialImgs materialImgs1 : materialImgs) {
                                //根据素材图片id删除素材链接
                                Integer rlink = materialMapper.deMaterialLink(materialImgs1.getId());
                                System.err.println("删除素材链接" + rlink + "行");
                            }

                        }
                    }
                }

        }


        }


    }

    /**
     * 修改分组
     * @param id
     * @param groupName
     * @return
     */
    @Override
    public Integer upGroupName(String id, String groupName,MultipartFile file,String account) {
        if(id.isEmpty() || groupName.isEmpty()){
            throw new UploadException("id或名称为空");
        }
        //文件名
        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //http://lfwd.cloudsmicro.com/img/mgg-shop/2.png
        // 上传后的路径
        String filePath = "//root//code//img//" + account + "-material//" + id + "//";
        // 新文件名
        fileName = id + suffixName;
        String groupImg = "http://lfwd.cloudsmicro.com/img/" + account + "-material/" + id + "/" + id + suffixName;
        saveFile(file, fileName, filePath);

        return materialMapper.upGroupName(id,groupName,groupImg);
    }

    /**
     * 搜索分组
     * @param account
     * @param groupName
     * @return
     */
    @Override
    public MaterialGroupVo findGroupByName(String account, String groupName) {
        if (null == account || account.isEmpty()) {
            System.err.println("没有account");
            throw new UploadException("没有account");
        }
       // int start = (page-1)*20;
        MaterialGroupVo materialGroupVo = new MaterialGroupVo();
        //获取总条数
        materialGroupVo.setCount(materialMapper.findGroupCountByName(account,groupName));
        ArrayList<MaterialGroup> materialGroups = materialMapper.findGroupByName(account,groupName);
        materialGroupVo.setMaterialGroup(materialGroups);

        return materialGroupVo;
    }


    /**
     * 新增素材
     * @param files 图片
     * @param materialName 素材名称
     * @param groupId 分组id
     * @param imgDescribe 图片描述
     * @return
     */
    @Override
    public Integer insertMaterial(MultipartFile[] files, String materialName, String groupId, String imgDescribe,String account,String price) {
        String types = "material";
        String fs = Arrays.toString(files);
        System.err.println(files.length);
        System.err.println("gid="+groupId);
        if (files.length == 0) {
            throw new UploadException("图片为空");
        }
        //根据groupId查询分组名字
        MaterialGroup materialGroup = materialMapper.fGroupNameByGpId(account,groupId);
        //素材
        Material m = new Material();
        //素材名称
        m.setMaterialName(materialName);
        //所属分组
        m.setGroupId(groupId);
        //图片描述
        m.setImgDescribe(imgDescribe);
        m.setAccount(account);
        m.setPrice(price);
        //商品id
        //m.setGoodsId(goodsId);
        //新增素材
        Integer row = materialMapper.insertMaterial(m);
        System.err.println("maId=="+m.getId());

        //新增素材图片
        int s = addMaImgs(files,materialName,materialGroup,m.getId(),account,groupId);
        System.err.println(s);
        return row;
    }

    /**
     * 根据id修改素材
     * @return
     */
    @Override
    public Integer upMaterial(String materialName,String groupId,String imgDescribe,String id,String price) {

        return materialMapper.upMaterial(materialName,groupId,imgDescribe,id,price);
    }

    /**
     * 根据id获取素材信息
     * @param id
     * @return
     */
    @Override
    public MaterialVo findMaterialById(String id) {
        Material material =materialMapper.findMaterialById(id);
        MaterialVo materialVo = new MaterialVo();
        materialVo.setMaterial(material);

        ArrayList<MaterialImgs> materialImgs = materialMapper.findImgsByMId(id);
        materialVo.setMaterialImgs(materialImgs);

        return materialVo;
    }

    /**
     * 根据id获取素材
     * @param id
     * @return
     */
    @Override
    public Material getMaterialById(String id) {
        Material material =materialMapper.findMaterialById(id);
        ArrayList<MaterialImgs> materialImgs = materialMapper.findImgsByMId(id);
        List<String> imgList = new ArrayList<>();
        for (MaterialImgs materialImgs1:materialImgs) {
            imgList.add(materialImgs1.getImgs());
        }
        if (imgList.size()!=0) {
            material.setImgList(imgList);
        }
        return material;
    }

    /**
     * 获取所有素材
     * @param account
     * @return
     */
    @Override
    public MaterialEO getMaterialAll(String account,int page) {
        if (null == account || account.isEmpty()) {
            System.err.println("没有account");
            throw new UploadException("没有account");
        }
        ArrayList<MaterialEVo> materialEVoList = new ArrayList<>();
        int start = (page-1)*20;
        //查看所有素材
        ArrayList<Material> material = materialMapper.findMaterialAll(account,start);
        for (Material m:material) {
            //根据分组ID查询名字
           MaterialGroup materialGroup = materialMapper.fGroupNameByGpId(account,m.getGroupId());
           if(null != materialGroup) {
               m.setGroupName(materialGroup.getGroupName());
           }
            MaterialEVo materialEVos = new MaterialEVo();
            materialEVos.setMaterial(m);
            //根据素材id查看素材图片
           ArrayList<MaterialImgs> materialImgs = materialMapper.findImgsByMId(m.getId());

            m.setImgList(materialImgs);

            System.err.println("service查看素材图片"+materialImgs);
            if(materialImgs.size() != 0){
                System.err.println("不为空");
                materialEVos.setImg(materialImgs.get(0).getImgs());
                materialEVoList.add(materialEVos);
            }else {
                materialEVoList.add(materialEVos);
            }

        }

        MaterialEO materialEO = new MaterialEO();
        materialEO.setMaterialEVos(materialEVoList);
        materialEO.setCount(materialMapper.findMaterialCountAll(account));

        return materialEO;
    }

    /**
     * 搜索素材
     * @param account
     * @param materialName
     * @param page
     * @return
     */
    @Override
    public MaterialEO findWebMaterialByName(String account, String materialName, int page,String groupId) {
        if (null == account || account.isEmpty()) {
            System.err.println("没有account");
            throw new UploadException("没有account");
        }
        int start = (page-1)*20;
         ArrayList<Material> materials = materialMapper.findWebMaterialByName(account,materialName,start,groupId);
        ArrayList<MaterialEVo> materialEVoList = new ArrayList<>();
        for (Material m:materials) {
            //根据分组ID查询名字
            MaterialGroup materialGroup = materialMapper.fGroupNameByGpId(account,m.getGroupId());
            if(null != materialGroup) {
                m.setGroupName(materialGroup.getGroupName());
            }
            MaterialEVo materialEVos = new MaterialEVo();
            materialEVos.setMaterial(m);
            //根据素材id查看素材图片
            ArrayList<MaterialImgs> materialImgs = materialMapper.findImgsByMId(m.getId());

            m.setImgList(materialImgs);

            if(materialImgs.size() != 0){
                System.err.println("不为空");
                materialEVos.setImg(materialImgs.get(0).getImgs());
                materialEVoList.add(materialEVos);
            }else {
                materialEVoList.add(materialEVos);
            }
        }
        MaterialEO materialEO = new MaterialEO();
        materialEO.setMaterialEVos(materialEVoList);
        String count = materialMapper.findMaterialCountByName(account,materialName,groupId);
        System.err.println(count);
        materialEO.setCount(count);

        return materialEO;
    }

    /**
     * 删除素材
     * @param ids
     * @return
     */
    @Override
    public void deMaterialById(String ids,String account) throws JSONException {
        List<String> list = new ArrayList<>();
        String str[] = ids.split(",");
        list = Arrays.asList(str);

        for(String id : list) {


            //根据素材id查询图片
            ArrayList<MaterialImgs> materialImgs = materialMapper.findMaImgsByGpId(id);
            for (MaterialImgs materialImgs1 : materialImgs) {
                //根据素材图片id删除素材链接
                Integer rlink = materialMapper.deMaterialLink(materialImgs1.getId());
                System.err.println("删除素材链接" + rlink + "行");
            }

            //图片
            Integer rImgs = materialMapper.deMaterialImgs(id);
            Integer r = materialMapper.deMaterialById(id);

        }


    }

    /**
     * 删除素材图片
     * @param id
     * @return
     */
    @Override
    public Integer deMateriaImglById(String id,String account) {
        Integer rlink = materialMapper.deMaterialLink(id);
        Integer r = materialMapper.deMateriaImglById(id);
        if(r==0){
            throw new DeleteException("删除失败");
        }
        return r;
    }

    /**
     * 修改新增素材图片
     * @param mid
     * @return
     */
    @Override
    public Integer insertMaterialImgs(String mid, MultipartFile file,String account) {
        if (file!=null&&!file.isEmpty()) {
            Material material = materialMapper.findMaterialById(mid);
            //根据分组ID查询名字
            MaterialGroup materialGroup = materialMapper.fGroupNameByGpId(account,material.getGroupId());
            //文件名
            String fileName = file.getOriginalFilename();
            // 后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //http://lfwdcdn.cloudsmicro.com/img/mgg-shop/2.png
            // 上传后的路径
            String filePath = "//root//code//img//" + account + "-material//" + material.getGroupId() + "//"+mid + "//";
            Integer count = materialMapper.findMaImgCountByMId(mid);
            // 新文件名
            fileName = mid + "-" + ++count + suffixName;
            saveFile(file, fileName, filePath);


            String img = "http://lfwdcdn.cloudsmicro.com/img/" + account + "-material/" + material.getGroupId() + "/" + mid +"/"+mid + "-" + count + suffixName;
            Integer e = materialMapper.insertMaterialImgs(mid,img);
         return e;
        }else {
            throw new UploadException("没有收到文件");
        }


    }


    //新增素材图片
    private int addMaImgs(MultipartFile[] files, String materialName, MaterialGroup materialGroup, String mid, String account,String groupId){
        int c = 0;
        int s = 0;
        //遍历图片
        for (MultipartFile multipartFile : files) {
            // 文件名
            String fileName = multipartFile.getOriginalFilename();
            // 后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            // 上传后的路径
            String filePath = "//root//code//img//" + account + "-material//"+ groupId + "//"+mid+"//";
            // 新文件名
            fileName = mid + "-" + ++c + suffixName;
            //保存
            saveFile(multipartFile,fileName,filePath);
            //新增到素材图片
            String img = "http://lfwdcdn.cloudsmicro.com/img/" + account + "-material/" + groupId +"/"+mid+"/"+mid + "-" + c + suffixName;
            int row = materialMapper.insertMaterialImgs(mid,img);
            s=s+row;
        }
        return s;
    }

    //保存文件
    private void saveFile(MultipartFile multipartFile, String fileName, String filePath) {
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new com.burgeon.backend.service.ex.UploadException("系统错误");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new com.burgeon.backend.service.ex.UploadException("系统错误");
        }
    }

    /**
     * 添加素材图片链接
     * @param miid
     * @param gid
     * @return
     */
    @Override
    public Integer addMaterialLink(String miid, String gid) {
        return materialMapper.addMaterialLink(miid,gid);
    }

    /**
     * 根据id查看连接二维码
     * @param id
     * @return
     */
    @Override
    public String findMaLinkById(String id) {
        MaterialLink materialLink = materialMapper.findMaLinkById(id);
        String link = "http://bipthq.natappfree.cc:8081/wei_material/index.html?"+materialLink.getGid();
        return link;
    }

    /**
     * 根据素材图片id查看链接
     * @param mid
     * @param gid
     * @return
     */
    @Override
    public Integer upMaLinkByMid(String mid, String gid) {
        if(mid.isEmpty() || gid.isEmpty()){
            throw new UploadException("素材图片或商品id空");
        }
        return materialMapper.upMaLinkByMid(mid,gid);
    }

    /**
     * 根据id查询商品信息
     * @param id
     * @return
     */
    @Override
    public MaterialGoods findGoodsById(String id) {
        System.err.println(id);
        try {
            //根据id查询商品
            MaterialGoods data = materialMapper.getGoodsById(id);
            //根据商品id查询商品banner图
            List banner = goodsMapper.findGoodsBanner(data.getId());
            data.setBanner(banner);

            System.err.println(data);
            return data;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }


}
